package com.jayhuang.user_center.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jayhuang.user_center.common.ErrorCode;
import com.jayhuang.user_center.exception.BusinessException;
import com.jayhuang.user_center.utils.Result;
import com.jayhuang.user_center.contant.UserConstant;
import com.jayhuang.user_center.pojo.User;
import com.jayhuang.user_center.pojo.response.SafetUserResponse;
import com.jayhuang.user_center.mapper.UserMapper;
import com.jayhuang.user_center.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author HUANG
 * @description  针对表【user(用户表)】的数据库操作Service实现
 * @createDate  2024-10-23 20:02:54
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    // 数据层
    @Resource
    private UserMapper userMapper;

    // 盐值， 混淆密码
    private final String SALT = "jangly";

    @Override
    public Result userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 校验
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户小于4位");
        }
        if (userPassword.length() < 8 || checkPassword.length() > 16) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度为8-16位");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编号小于4位");
        }

        // 校验编号是否重复
        QueryWrapper<User> queryWrapperCode = new QueryWrapper<>();
        queryWrapperCode.eq("planetCode", planetCode);
        long planetCodeCount = this.count(queryWrapperCode);
        if (planetCodeCount > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编号已存在");
        }
        // 校验账户不能包含特殊字符
        //账户不能包含特殊字符，使用正则   `表达式
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户不能包含特殊字符");
        }
        // 校验账户是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账户已存在");
        }
        // 校验密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不一致");
        }
        // 密码加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(md5DigestAsHex);
        user.setPlanetCode(planetCode);
        boolean saveUser = this.save(user);
        if (!saveUser) {
            return Result.error(400,"注册失败");
        }
        return Result.success(200,"注册成功",Math.toIntExact(user.getId()));
    }

    @Override
    public SafetUserResponse doLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 校验
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8 || userPassword.length() > 16) {
            return null;
        }
        // 校验账户不能包含特殊字符
        //账户不能包含特殊字符，使用正则表达式
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 密码加密
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", md5DigestAsHex);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 脱敏
        SafetUserResponse safetUser = new SafetUserResponse();
        BeanUtils.copyProperties(user, safetUser);
        // 记录登录状态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetUser);
        return safetUser;
    }

    @Override
    public void userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
    }
}




